from django.db import transaction
from rest_framework import serializers
from apps.goods.models import SKU, GoodsCategory, SPU, SpecificationOption, SPUSpecification, SKUSpecification


class SKUSpecificationSerialzier(serializers.ModelSerializer):
    """
        SKU规格表序列化器
    """
    spec_id = serializers.IntegerField(     
         
          
           
            
             
              
               
                 

    )
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification  # SKUSpecification中sku外键关联了SKU表
        fields = ("spec_id", 'option_id')


class SKUSerializer(serializers.ModelSerializer):
    # 添加2个字段来接收 category_id 和 spu_id
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()
    # 自己定义spu和category字段为 StringRelatedField
    spu = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)

    specs = SKUSpecificationSerialzier(many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    # 前端所有的数据
    def create(self, validated_data):
        # validated_data

        # 1.先把规格手机  获取到  并从字典删除
        specs = validated_data.pop('specs')

        with transaction.atomic():
            # 获取保存点
            save_point = transaction.savepoint()
            try:
                # 2.先保存sku
                sku = SKU.objects.create(**validated_data)

                # 3.循环specs保存规格
                for spec in specs:
                    SKUSpecification.objects.create(sku=sku, **spec)
            except Exception as e:
                print(e)
                transaction.savepoint_rollback(save_point)
            else:
                transaction.savepoint_commit(save_point)
            # 返回 sku数据
            return sku

    def update(self, instance, validated_data):
        # 先把规格数据  获取到  并从字典里删除
        specs = validated_data.pop('specs')
        # 调用父类update方法
        super().update(instance, validated_data)
        # 循环更新  specs更新规格的选
        for spec in specs:
            # 获取新的数据里的选
            new_spec_id = spec.get('spec_id')
            new_option_id = spec.get('option_id')
            SKUSpecification.objects.filter(sku=instance, spec_id=new_spec_id).update(option_id=new_option_id)

        return instance


class SKUCategorieSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = "__all__"


class GoodsSimpleSerializer(serializers.ModelSerializer):

    class Meta:
        model = SPU
        fields = '__all__'


class GoodsOptineSerializer(serializers.ModelSerializer):

    class Meta:
        model = SpecificationOption
        fields = ('id', 'value')


class GoodsSpecSerialzier(serializers.ModelSerializer):

    spu = serializers.StringRelatedField()
    spu_id = serializers.IntegerField()
    # 关联序列化返回 规格选项信息
    # 使用规格选项序列化器
    options = GoodsOptineSerializer(many=True)

    class Meta:

        model = SPUSpecification
        fields = "__all__"
